import glfw
from OpenGL.GL import *
import numpy as np
# 顶点着色器代码
vertex_shader_source = """
#version 330 core
layout (location = 0) in vec3 aPos;
void main()
{
    gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
}
"""

# 片段着色器代码
fragment_shader_source = """
#version 330 core
out vec4 FragColor;
void main()
{
    FragColor = vec4(1.0, 0.5, 0.2, 1.0);
}
"""

def main():
    # 初始化glfw
    if not glfw.init():
        return

    # 设置OpenGL版本号
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    
    # 创建窗口
    window = glfw.create_window(800, 600, "Simple Shader Example", None, None)
    if not window:
        glfw.terminate()
        return

    # 设置当前窗口上下文
    glfw.make_context_current(window)

    # 编译顶点着色器
    vertex_shader = glCreateShader(GL_VERTEX_SHADER)
    glShaderSource(vertex_shader, vertex_shader_source)
    glCompileShader(vertex_shader)

    # 编译片段着色器
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER)
    glShaderSource(fragment_shader, fragment_shader_source)
    glCompileShader(fragment_shader)

    # 创建着色器程序
    shader_program = glCreateProgram()
    glAttachShader(shader_program, vertex_shader)
    glAttachShader(shader_program, fragment_shader)
    glLinkProgram(shader_program)
    glUseProgram(shader_program)

    # 顶点数据
    vertices = [-0.5, -0.5, 0.0,  # 左下角
                0.5, -0.5, 0.0,   # 右下角
                0.0,  0.5, 0.0]   # 顶部

    vertices = np.array(vertices, dtype=np.float32)

    # 创建顶点缓冲对象
    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)

    # 创建顶点数组对象
    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), None)
    glEnableVertexAttribArray(0)

    # 渲染循环
    while not glfw.window_should_close(window):
        glClear(GL_COLOR_BUFFER_BIT)

        # 使用着色器程序
        glUseProgram(shader_program)

        # 绑定顶点数组对象
        glBindVertexArray(VAO)

        # 绘制三角形
        glDrawArrays(GL_TRIANGLES, 0, 3)

        # 交换缓冲区并轮询事件
        glfw.swap_buffers(window)
        glfw.poll_events()

    # 清理资源
    glfw.terminate()

if __name__ == "__main__":
    main()
 